﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using DTO;

namespace DAO
{
    public class DonHangSapGiaoDAO
    {
        public List<DonHangSapGiaoDTO> LayDS()
        {
            string sqlStr = "select hd.MaHoaDon, hd.TenNguoiNhan, hd.SDTNguoiNhan , hd.GiaoDen, hd.NgayGiao, datediff(ss,getdate(),hd.NgayGiao) ";
            sqlStr = sqlStr + "from HOADON hd ";
            sqlStr = sqlStr + "where datediff(mi,getdate(),hd.NgayGiao) <= 2880 and datediff(mi,getdate(),hd.NgayGiao) >= 1 ";
            sqlStr = sqlStr + "order by hd.NgayGiao";

            SqlConnection cn = DataProvider.ConnectDB();
            SqlCommand cm = new SqlCommand(sqlStr, cn);
            SqlDataReader dr = cm.ExecuteReader();
            List<DonHangSapGiaoDTO> ds = new List<DonHangSapGiaoDTO>();
            while (dr.Read())
            {
                DonHangSapGiaoDTO dto = new DonHangSapGiaoDTO();
                dto.MaHoaDon = dr.GetInt32(0);
                dto.TenNguoiNhan = dr.GetString(1);
                dto.SDTNguoiNhan = dr.GetString(2);
                dto.DiaChi = dr.GetString(3);
                dto.NgayGiao = dr.GetDateTime(4);              
                dto.ThoiGianConLai = dr.GetInt32(5)/60;
                ds.Add(dto);
            }

            dr.Close();
            cn.Close();
            return ds;
        }

        public List<ChiTietDonHangSapGiaoDTO> LayChiTietDHTheoMaDH(int ma)
        {
            string sqlStr = "select cthd.MaHoaDon, mh.TenMatHang, xx.TenXuatXu, dv.TenDonViTinh, cthd.SoLuong, cthd.DonGia, cthd.SoLuong*cthd.DonGia ";
            sqlStr = sqlStr + "from CHITIETHOADON cthd, MATHANG mh, XUATXU xx, DONVITINH dv ";
            sqlStr = sqlStr + "where cthd.MaHoaDon = " + ma;
            sqlStr = sqlStr + "and cthd.MaMatHang = mh.MaMatHang and cthd.MaXuatXu = xx.MaXuatXu and cthd.MaDonViTinh = dv.MaDonViTinh and mh.MaXuatXu = xx.MaXuatXu";
            SqlConnection cn = DataProvider.ConnectDB();
            SqlCommand cm = new SqlCommand(sqlStr, cn);
            SqlDataReader dr = cm.ExecuteReader();
            List<ChiTietDonHangSapGiaoDTO> ds = new List<ChiTietDonHangSapGiaoDTO>();
            while (dr.Read())
            {
                ChiTietDonHangSapGiaoDTO dto = new ChiTietDonHangSapGiaoDTO();
                dto.MaHoaDon = dr.GetInt32(0);
                dto.TenMatHang = dr.GetString(1);
                dto.XuatXu = dr.GetString(2);
                dto.DonViTinh = dr.GetString(3);
                dto.SoLuong = dr.GetInt32(4);
                dto.DonGia = dr.GetDouble(5);
                dto.TongTien = dr.GetDouble(6);
                ds.Add(dto);
            }

            dr.Close();
            cn.Close();
            return ds;
        }
    }
}
